package com.magold.start.splash;

import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.AlphaModifier;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.util.call.Callback;
import org.andengine.util.modifier.IModifier;

import com.magold.sprite.IMultiTextureSprite;

public class CiAppearEvent implements ISplashEvent{
	
	
	protected IMultiTextureSprite mlCiSprite;
	protected IMultiTextureSprite mrCiSprite;
	private final IEntity mCenterCiSprite;

	private final Callback<Object> mCallback;
	private final boolean mIsAppear;
	public CiAppearEvent(boolean pIsAppear, IMultiTextureSprite plBlueCiSprite,
			IMultiTextureSprite prBlueCiSprite,
			IMultiTextureSprite pRedCiSprite, Callback<Object> pCallback) {
		mlCiSprite = plBlueCiSprite;
		mrCiSprite = prBlueCiSprite;
		mCenterCiSprite = pRedCiSprite;
		
		mCallback = pCallback;
		mIsAppear = pIsAppear;
	}

	@Override
	public void perform() {
		if (mIsAppear) {
			appear();
		} else {
			disappear();
		}
	}
	
	private void disappear() {
		final IEntityModifierListener listener = new IEntityModifierListener() {
			
			@Override
			public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
			}
			
			@Override
			public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
				mCallback.onCallback(null);
			}
		};
		Callback<Object> callback = new Callback<Object>() {

			@Override
			public void onCallback(Object pCallbackValue) {
				AlphaModifier modifier = new AlphaModifier(1.0f, 1.0f, 0.0f, listener);
				
				mCenterCiSprite.registerEntityModifier(modifier);
				mlCiSprite.registerEntityModifier(modifier.deepCopy());
				mrCiSprite.registerEntityModifier(modifier.deepCopy());
			}
		};
		SplashCrewHandler.customize(SplashCrewHandler.LEFT_OFFSET, SplashCrewHandler.OX, false);
		SplashCrewHandler screwHandler = new SplashCrewHandler(mlCiSprite, mrCiSprite, callback);
		mlCiSprite.registerUpdateHandler(screwHandler);
		
	}
	
	private void appear() {
		IEntityModifierListener listener = new IEntityModifierListener() {
			
			@Override
			public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
			}

			@Override
			public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
				SplashCrewHandler.customize(SplashCrewHandler.OX, SplashCrewHandler.LEFT_OFFSET, true);
				SplashCrewHandler screwHandler = new SplashCrewHandler(mlCiSprite, mrCiSprite, mCallback);
				mlCiSprite.registerUpdateHandler(screwHandler);
			}
		};
		AlphaModifier modifier = new AlphaModifier(1.0f, 0.0f, 1.0f, listener);
		mCenterCiSprite.registerEntityModifier(modifier);
		mlCiSprite.registerEntityModifier(modifier.deepCopy());
		mrCiSprite.registerEntityModifier(modifier.deepCopy());
	}

}
